<script setup lang="ts">
import { ref, onMounted, reactive, watch, toRaw } from "vue";
import { ElMessage, ElForm, ElFormItem, ElRadioGroup, ElRadio, ElSelect, ElOption, ElInputNumber, ElButton, ElMessageBox, ElDivider } from "element-plus";
import { useRoute } from "vue-router";
import { useI18n } from 'vue-i18n';
import { getProductDeptGroupConfigsApi, setProductDeptGroupConfigsApi } from '@/api/configs/productDeptConfig';
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";

const { t } = useI18n();

const configGroupName = "dataSavePolicy";

const props = defineProps<{
  searchForm: {
    default: {
      deptId: 0,
      productId: 0,
    };
  };
}>();

// 定义配置项类型
interface DataSavePolicyConfig {
  isSave: boolean; //
  timeBy: 0 | 1 | 2 | 3 | 4; //时间分片机制
  expireTime: number; //默认数据过期时间 (天)
}

// // 设备分区维度
// const partByOptions = [
//   { label: '按分组(该分组设备数据集中在一起)', val: '1' },
//   { label: '按设备(常用于设备数据独立，设备之间不需要数据关联)', val: '2' }
// ];

// 时间分区维度
const timeByOptions = [
  { label: t('configs.deptProductConfigPage.dataSavePolicy.timeByOptions.yearly'), val: 1 },
  { label: t('configs.deptProductConfigPage.dataSavePolicy.timeByOptions.monthly'), val: 2 },
  { label: t('configs.deptProductConfigPage.dataSavePolicy.timeByOptions.daily'), val: 3 },
];

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();
const defaultConfig :DataSavePolicyConfig=  {
  isSave: false,
  timeBy: 0,
  expireTime: 365,
}
// 初始化表单数据
const formData = reactive<{
  productId: number;
  deptId: number;
  groupName: string;
  config: DataSavePolicyConfig;
  updatedAt: string;
}>({
  productId: 0,
  deptId: 0,
  groupName: configGroupName,
  config:Object.assign({}, defaultConfig),
  updatedAt: ''
});

// 表单验证规则
const rules = reactive({
  'config.isSave': [
    { required: true, message: t('configs.deptProductConfigPage.common.validationFailed'), trigger: 'change' }
  ],
  'config.timeBy': [
    { required: true, message: t('configs.deptProductConfigPage.common.validationFailed'), trigger: 'change' }
  ],
  'config.expireTime': [
    { required: true, message: t('configs.deptProductConfigPage.common.validationFailed'), trigger: 'change' },
    { type: 'number', min: 7, message: t('configs.deptProductConfigPage.dataSavePolicy.expireTime') + ' ' + 'cannot be less than 7 days', trigger: 'change' }
  ],
});
onMounted(() => {
  if (props.searchForm) {
    formData.productId = props.searchForm.productId;
    formData.deptId = props.searchForm.deptId;
    loadConfigData();
  }
});
watch(() => props.searchForm, (newVal:any) => {
  if (newVal) {
    console.log(newVal);
    formData.productId = newVal.productId;
    formData.deptId = newVal.deptId;
    loadConfigData();
  }
},{
  deep: true
});

const loadConfigData = () => {
  console.log(toRaw(formData))
  if (formData.productId && formData.deptId) {
    getProductDeptGroupConfigsApi({
      productId: formData.productId,
      deptId: formData.deptId,
      groupName: formData.groupName
    }).then(res => {
      if (res.code === 0 && res.data?.configs) {
        formData.updatedAt = res.data.updatedAt || '';
        try {
          const configData = JSON.parse(res.data.configs[0]?.configValue || '{}');
          Object.assign(formData.config, configData);
        } catch (e) {
          console.error('解析配置数据失败', e);
        }
      }
    });
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    // 1. 先进行表单验证
    await formRef.value.validate();

    // 2. 准备提交数据
    const submitData = {
      productId: formData.productId,
      deptId: formData.deptId,
      groupName: formData.groupName,
      configs: [{
        configKey: 'dataSavePolicy',
        configValue: JSON.stringify(formData.config),
        configDesc: ''
      }]
    };

    // 3. 验证通过后显示二次确认框
    ElMessageBox.confirm(
      t('configs.deptProductConfigPage.dataSavePolicy.confirmSubmit'),
      'Confirm Submit',
      {
        confirmButtonText: t('configs.deptProductConfigPage.common.confirmButtonText'),
        cancelButtonText: t('configs.deptProductConfigPage.common.cancelButtonText'),
        type: 'warning',
      }
    ).then(async () => {
      await setProductDeptGroupConfigsApi(submitData);
      ElMessage.success(t('configs.deptProductConfigPage.common.saveSuccess'));
    }).catch(() => {
      // 用户取消提交
      ElMessage.info(t('configs.deptProductConfigPage.common.saveCancelled'));
    });
  } catch (error) {
    ElMessage.error(t('configs.deptProductConfigPage.common.validationFailed'));
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};

const formatTimestamp = (timestamp:any) => {
  if(!timestamp || isNaN(timestamp)) {
    return '';
  }
  timestamp = Number(timestamp);
  const date = new Date(timestamp * 1000); // 秒转毫秒
  return date.toLocaleString(); // 返回本地格式的日期时间
}

</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="160px" class="form-container">
<!--    <el-form-item label="产品" prop="productId">-->
<!--      <el-input :value="formData.productId " disabled />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="部门" prop="deptId">-->
<!--      <el-input :value="formData.deptId" disabled />-->
<!--    </el-form-item>-->
    <el-form-item :label="t('configs.deptProductConfigPage.dataSavePolicy.configGroupName')" prop="groupName">
      <el-input v-model="formData.groupName" disabled />
    </el-form-item>
    <el-form-item :label="t('configs.deptProductConfigPage.dataSavePolicy.isSave')" prop="config.isSave">
      <el-radio-group v-model="formData.config.isSave" style="display: flex; flex-direction: column; align-items: flex-start">
        <el-radio :label="false">{{t('buttons.no')}}</el-radio>
        <el-radio :label="true">{{t('buttons.yes')}}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item :label="t('configs.deptProductConfigPage.dataSavePolicy.timeBy')" prop="config.timeBy">
      <el-radio-group v-model="formData.config.timeBy" style="display: flex; flex-direction: column; align-items: flex-start">
        <el-radio :label="o.val" v-for="(o,index) in timeByOptions" :key="index">{{o.label}}</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 数据过期时间 -->
    <el-form-item :label="t('configs.deptProductConfigPage.dataSavePolicy.expireTime')" prop="config.expireTime">
      <el-input-number
        v-model.number="formData.config.expireTime"
        :min="7"
        :step="1"
        :placeholder="t('configs.deptProductConfigPage.dataSavePolicy.expireTime')"
      />
      <div class="form-hint">{{ t('configs.deptProductConfigPage.dataSavePolicy.expireTimeHint') }}</div>
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item :label="t('configs.deptProductConfigPage.dataSavePolicy.updatedAt')">
      <el-input :value="formatTimestampToDatetime(formData.updatedAt)" disabled :placeholder="t('configs.deptProductConfigPage.common.noUpdateTime')" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">{{ t('configs.deptProductConfigPage.dataSavePolicy.submit') }}</el-button>
      <el-button @click="resetForm">{{ t('configs.deptProductConfigPage.dataSavePolicy.reset') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 30px;
}

.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}
</style>
